package com.rc.web.service.impl;


import com.rc.web.utils.JsonUtils;
import com.rc.web.utils.VivoAuth;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;

/**
 * AI绘画服务
 */
@Service
public class PaintingService {


    /**
     * 提交绘画任务
     * @param user 用户输入内容
     * @param prompt 提示词
     * @return API响应结果
     * @throws UnsupportedEncodingException
     */
    public String task_submit(String user ,String prompt) throws UnsupportedEncodingException, UnsupportedEncodingException {
        final String APP_ID = "2025985389";
        final String APP_KEY = "eAkRKtYXOawsmtVv";
        final String METHOD = "POST";
        final String URI = "/api/v1/task_submit";
        final String DOMAIN = "api-ai.vivo.com.cn";

        // 定义请求体数据
        Map<String, Object> data = new HashMap<>();
        data.put("height", 768);
        data.put("width", 576);
        data.put("prompt", user+prompt);
        //唯美写实风格
        data.put("styleConfig", "4cbc9165bc615ea0815301116e7925a3");  //55c682d5eeca50d4806fd1cba3628781  默认
        // 将请求体数据转换为 JSON 格式
        String requestBody = JsonUtils.toJson(data);
        // 请求参数
        Map<String, Object> query = new HashMap<>();
        String queryString = mapToQueryString(query);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        headers.add("Content-Type", "application/json");
        String url = String.format("http://%s%s", DOMAIN, URI);
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();
    }



    /**
     * 查询任务进度
     * @param text 任务ID
     * @return API响应结果
     * @throws UnsupportedEncodingException
     */
    public String taskProgress(String text) throws UnsupportedEncodingException {
        final String APP_ID = "2025985389";
        final String APP_KEY = "eAkRKtYXOawsmtVv";
        final String METHOD = "GET";
        final String URI = "/api/v1/task_progress";
        final String DOMAIN = "api-ai.vivo.com.cn";

        //请求url参数
        Map<String, Object> data = new HashMap<>();
        data.put("task_id",text);
        String queryString = mapToQueryString(data);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, queryString);
        String url = String.format("http://%s%s?%s", DOMAIN, URI,queryString);
        headers.add("Content-Type", "application/json");
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();
    }



    /**
     * 将Map转换为URL查询字符串
     * @param map 参数Map
     * @return 查询字符串
     */
    public static String mapToQueryString(Map<String, Object> map) {
        if (map.isEmpty()) {
            return "";
        }
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (queryStringBuilder.length() > 0) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey());
            queryStringBuilder.append("=");
            queryStringBuilder.append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }

    /**
     * 根据用户需求生成并返回图片
     *
     * @param userInput 用户输入的需求
     * @return 图片的字节数组
     * @throws UnsupportedEncodingException
     */
    public String generateImage(String userInput) throws UnsupportedEncodingException, InterruptedException {

        String prompt ="";
        if(userInput.length()<20){
            // 构建提示词
            prompt = "。根据用户的要求，生成一幅符合用户要求的图片。";
        }
        else{
            prompt = "这是一首古诗，请根据古诗的意境生成图片。" +
                    "图片应该具有中国传统水墨画风格，" +
                    "画面要体现古诗中描述的场景和情感，" +
                    "图片上不要有文字，"+
                    "整体风格要古典雅致，富有诗意。";
        }
        // 提交任务并获取任务ID
        String result = task_submit(userInput, prompt);
        Map<String, Object> responseMap = JsonUtils.fromJson(result, HashMap.class);
        Map<String, Object> resultMap = (Map<String, Object>) responseMap.get("result");
        String taskId = (String) resultMap.get("task_id");

        // 轮询任务状态直到完成
        while (true) {
            String progressResult = taskProgress(taskId);
            Map<String, Object> progressMap = JsonUtils.fromJson(progressResult, HashMap.class);
            Map<String, Object> progressResultMap = (Map<String, Object>) progressMap.get("result");

            // 检查任务是否完成
            boolean finished = (boolean) progressResultMap.get("finished");
            if (finished) {
                List<String> imageUrls = (List<String>) progressResultMap.get("images_url");
                if (imageUrls != null && !imageUrls.isEmpty()) {
                    String imageUrl = imageUrls.get(0);

                    // 确保URL是完整的
                    if (imageUrl != null && !imageUrl.startsWith("http")) {
                        imageUrl = "http://" + imageUrl;
                    }
                    System.out.println("Image URL: " + imageUrl);

                    return imageUrl;

                }
                break;
            }

            // 等待一段时间再重试
            Thread.sleep(5000); // 5秒
        }

        throw new RuntimeException("Task completed but no image URL found");
    }


    /**
     * 根据用户需求生成并返回海报图片
     * @param userInput 用户输入的需求
     * @return 海报图片的URL
     * @throws UnsupportedEncodingException
     * @throws InterruptedException
     */
    public String generatePoster(String userInput) throws UnsupportedEncodingException, InterruptedException {
        // 构建海报专用提示词
        String prompt = "这是一张海报设计需求，请根据以下要求生成海报图片：" +
                "1. 海报尺寸为1080x1920像素（竖版）" +
                "2. 设计风格要唯美、优雅、吸引眼球" +
                "3. 包含适当的留白和视觉层次" +
                "4. 色彩搭配要和谐统一" +
                "5. 图片上一定不要包含任何文字内容";

        // 提交任务并获取任务ID
        String result = task_submit(userInput, prompt);
        HashMap responseMap = JsonUtils.fromJson(result, HashMap.class);
        Map<String, Object> resultMap = (Map<String, Object>) responseMap.get("result");
        String taskId = (String) resultMap.get("task_id");

        // 轮询任务状态直到完成
        while (true) {
            String progressResult = taskProgress(taskId);
            Map<String, Object> progressMap = JsonUtils.fromJson(progressResult, HashMap.class);
            Map<String, Object> progressResultMap = (Map<String, Object>) progressMap.get("result");

            // 检查任务是否完成
            boolean finished = (boolean) progressResultMap.get("finished");
            if (finished) {
                List<String> imageUrls = (List<String>) progressResultMap.get("images_url");
                if (imageUrls != null && !imageUrls.isEmpty()) {
                    String imageUrl = imageUrls.get(0);

                    // 确保URL是完整的
                    if (imageUrl != null && !imageUrl.startsWith("http")) {
                        imageUrl = "http://" + imageUrl;
                    }
                    System.out.println("Poster Image URL: " + imageUrl);

                    return imageUrl;
                }
                break;
            }

            // 等待一段时间再重试
            Thread.sleep(5000); // 5秒
        }

        throw new RuntimeException("Task completed but no poster image URL found");
    }


    /**
     * 根据图片URL下载图片并转换为MultipartFile对象
     * @param imageUrl
     * @return
     * @throws IOException
     */
    public MultipartFile downloadImage(String imageUrl) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(imageUrl);
            request.setHeader("User-Agent", "Mozilla/5.0");

            try (CloseableHttpResponse response = httpClient.execute(request);
                 InputStream inputStream = response.getEntity().getContent()) {

                // 获取文件名和扩展名
                String fileName = extractFileName(imageUrl);
                String contentType = response.getEntity().getContentType().getValue();

                // 读取图片数据
                byte[] bytes = inputStream.readAllBytes();

                // 创建MultipartFile对象
                return new MockMultipartFile(
                        "file",           // 表单字段名
                        fileName,          // 原始文件名
                        contentType,      // 内容类型
                        bytes             // 文件内容
                );
            }
        }
    }

    public static String extractFileName(String url){
        // 从URL中提取文件名
        String[] parts = url.split("/");
        String lastPart = parts[parts.length - 1];

        // 移除查询参数
        return lastPart.split("[?#]")[0];
    }

}
